package com.ajun.work.round;

import com.ajun.common.ConnectionFactoryBuilder;
import com.ajun.common.QueueConstants;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * work 轮询模式 - work2
 *
 * @author AJun
 * @date 2021-07-14
 */
@Slf4j
public class Work2 {

    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            // 创建连接 Connection
            connection = ConnectionFactoryBuilder.getConnection("消费者 work2");
            // 获取通道 Channel
            channel = connection.createChannel();
            Channel finalChannel = channel;
            // 接收消息
            finalChannel.basicConsume(QueueConstants.WORK_ROUND_QUEUE, true,
                (consumerTag, message) -> {
                    log.debug("Work-2 消息接收成功, message => {}", new String(message.getBody(), StandardCharsets.UTF_8));
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                },
                consumerTag ->
                    log.error("消息接收失败")
            );
            log.debug("Work-2 开始 接收消息...");
            System.in.read();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            ConnectionFactoryBuilder.close(channel, connection);
        }
    }
}
